<?php
namespace trading\service;

use herosphp\core\Loader;
use herosphp\bean\Beans;
use herosphp\core\Log;
use api\utils\PayApiClient;
use utils\x1\MyNumber;

class OrderService extends CommonService{

    private $orderModel = null;
    private $orderProductModel = null;
    private $orderLogModel = null;
    private $contractService = null;
    private $productService = null;
    private $remindService = null;

    public function __construct($model) {
        parent::__construct($model);
        $this->orderModel = Loader::model($model);
        $this->orderProductModel = Loader::model('tradingOrderProduct');
        $this->orderLogModel = Loader::model('tradingOrderLog');
        $this->contractService = Beans::get('trading.tradingContract.service');
        $this->productService = Beans::get('product.product.service');
        $this->remindService = Beans::get('message.messageRemind.service');
    }

    /**
     * 支付类型
     * @param $k
     * @return mixed
     */
    public function getPaywayText($k='__all'){
        $arr=array('0'=>'线上支付','1'=>'线下支付');
        return $k=='__all'?$arr:$arr[$k];
    }

    /**
     * 支付类型2
     * @param $k
     * @return mixed
     */
    public function getPaywayText2($k='__all'){
        $arr=array('0'=>'线上','1'=>'线下');
        return $k=='__all'?$arr:$arr[$k];
    }

    /**
     * 订单状态
     * @param $k
     * @return mixed
     */
    public function getPaystatusText($k='__all'){
        $arr=array('0'=>'待用户议价','1'=>'待卖家确认','2'=>'待买家确认','3'=>'待支付','4'=>'待确认收款','5'=>'待发货','6'=>'已发货','7'=>'已完成','8'=>'已取消');
        return $k=='__all'?$arr:$arr[$k];
    }

    /**
     * 配送方式
     * @param $k
     * @return mixed
     */
    public function getShippingwayText($k='__all'){
        $arr=array('0'=>'卖家配送','1'=>'买家自提');
        return $k=='__all'?$arr:$arr[$k];
    }

    /**
     * 订单日志轨迹
     * @param string $k
     * @param string $type
     * @return array|mixed
     */
    public function getOrderLogText($k='__all',$type=0){
        $arr=array('0'=>'您提交了订单，请尽快付款完成订单','1'=>'您的订单已付款成功','2'=>'您的订单已经备货完成','3'=>'您的订单已发货完成','4'=>'您的订单确认收货成功','5'=>'感谢您本次购物，欢迎您再次光临！','6'=>'您的订单由于超出限定时间不付款，已被系统取消此订单','7'=>'卖家已确认收款，订单状态变更为已支付','8'=>'卖家已取消订单','9'=>'您已取消订单');
        if($type==1){//双方确认模式
            $arr = array('0'=>'订单提交成功，请等待卖家确定订单信息','1'=>'卖家确认订单','2'=>'买家已确认订单，请及时付款');
        }
        return $k=='__all'?$arr:$arr[$k];
    }

    /**
     * 交易模式
     * @param int $type
     * @return mixed
     */
    public function getOrderMode($type=0){
        $orderModel = $this->orderModel;
        switch($type){
            case 'DirectTrade'://直接交易
                $order_mode = $orderModel::DIRECTRADE;
                $order_status = $orderModel::ORDER_STATUS_UNPAY;
                break;
            case 'B2CConfirm'://买卖双方确认
                $order_mode = $orderModel::B2CCONFIRM;
                $order_status = $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION;
                break;
            case 'Bargaining'://用户议价
                $order_mode = $orderModel::BARGAINING;
                $order_status = $orderModel::WAIT_FOR_USER_BARGAINING;
                break;
            default://直接交易
                $order_mode = $orderModel::DIRECTRADE;
                $order_status = $orderModel::ORDER_STATUS_UNPAY;
                break;
        }
        return array('order_mode'=>$order_mode,'order_status'=>$order_status);
    }

    /**
     * 写入用户操作消息中心
     * @param $member_id
     * @param $order_no
     * @return mixed
     */
    public function addMessage($member_id,$order_no,$type){
        $messageService = Beans::get('message.message.service');
        $memberService = Beans::get('member.member.service');
        $member_info = $memberService->getUsernameById($member_id);
        return $messageService->addMessage($member_id,$type, array('member_name' => $member_info['username'], 'order_no' => $order_no));

    }

    /**
     * 检查订单是否属于用户的
     * @param $id
     * @param $member_id
     * @return bool
     */
    public function checkOrder($id,$member_id){
        if($id){
            $item = $this->orderModel->getItem($id);
            if(!$item || !$member_id || $item['member_id'] != $member_id) return false;
            return true;
        }else{
            return false;
        }
    }

    /**
     * 添加订单
     * @param array $data 需要添加的信息
     * @return bool|int
     */
    public function addOrder($data){
        $orderModel = $this->orderModel;

        if(!isset($data['product']['product_id'])) return -1;//订单没有产品

        $data['order_time'] = myNow();
        $data['order_status'] = 0;
        $MyNumber = new MyNumber(appId());
        $order_no = $MyNumber->build_no('dd');
        $data['order_no'] = $order_no;
        $order_life = C('order_life');
        $last_time = date('Y-m-d H:i:s',time()+$order_life*60);

        $product_items = $this->productService->getProductsByIds($data['product']['product_id'],$data['member_id']);
        $product_arr = array();
        foreach($product_items as $v){
            $product_arr[$v['id']] = $v;
        }
        $total_price = 0;
        $total_actual_price = 0;
        $product_data = array();

        //开启事物
        $this->beginTransaction();

        if($data['add_type']==$orderModel::ADD_TYPE_USER){//用户添加的订单

            //交易模式
            $order_mode = C('order_mode');
            $mode_info = $this->getOrderMode($order_mode);
            $data['order_mode'] = $mode_info['order_mode'];
            $data['order_status'] = $mode_info['order_status'];

            //删除购物车产品
            $cartService = Beans::get('trading.tradingCart.service');
            if($data['isCart']==1 && !$cartService->delCartProducts($data['member_id'],$data['product']['product_id'])){
                $this->rollback();
                return false;
            }

        }else{

            //运营商添加的订单直接交易
            $data['order_mode'] = $orderModel::DIRECTRADE;
            $data['order_status'] = $orderModel::ORDER_STATUS_UNPAY;

        }

        foreach($data['product']['product_id'] as $k=>$v){
            $product_quantity = setFloat($data['product']['product_quantity'][$k],3);
            $residual = $product_arr[$v]['quantity']-$product_arr[$v]['freeze_quantity'];//产品剩余库存
            if(bccomp($product_quantity,$residual,3) == 1){
                $this->rollback();
                return -2;//超出现有库存
            }
            $title = $product_arr[$v]['type_name'].'/'.$product_arr[$v]['product_name'].'/'.$product_arr[$v]['factory_name'].'/'.$product_arr[$v]['brand_name'].'<br/>货品规格(KG/袋)：'.$product_arr[$v]['pkg_size'];
            $attribute = array(
                'type_name'=>$product_arr[$v]['type_name'],
                'product_name'=>$product_arr[$v]['product_name'],
                'factory_name'=>$product_arr[$v]['factory_name'],
                'brand_name'=>$product_arr[$v]['brand_name'],
                'pkg_size'=>$product_arr[$v]['pkg_size'],
                'level'=>$product_arr[$v]['level'],
            );
            $product_price = bcmul($product_arr[$v]['sales_price'],$product_quantity,2);
            $product_actual_price = setFloat($data['product']['product_actual_price'][$k],2);
            $product_actual_price = $product_actual_price*1>0?$product_actual_price:$product_price;
            $total_price += $product_price;
            $total_actual_price += $product_actual_price;
            $product_data[] = array(
                'product_id'=>$v,
                'product_title'=>$title,
                'product_price'=>setFloat($product_arr[$v]['sales_price'],2),//单价
                'cost_price'=>setFloat($product_arr[$v]['cost_price'],2),//成本价
                'product_actual_price'=>$product_actual_price,
                'product_quantity'=>$product_quantity,
                'attribute'=>json_encode($attribute,JSON_UNESCAPED_UNICODE),
                'member_id'=>$data['member_id'],
            );
            //冻结商品库存数量API
            if(!$this->productService->freezeStock($v,$product_quantity)){
                $this->rollback();
                return false;
            }
        }
        $data['amount'] = $total_price;
        $data['actual_amount'] = $total_actual_price;

        //生成订单
        $id = $orderModel->add($data);
        if(!$id){
            $this->rollback();
            return false;
        }

        //写入订单商品信息
        foreach($product_data as $v){
            $v['order_id'] = $id;
            if(!$this->orderProductModel->add($v)){
                $this->rollback();
                return false;
            }
        }

        //配送方式 卖家配送--用户收货地址  自提--用户自提信息
        if($data['shipping_way'] == $orderModel::SHIPPING_WAY_SELLER){//卖家配送
            if(!$data['address']['id']){
                $this->rollback();
                return -3;
            }
            //收货地址
            $addressModel = Loader::model('memberReceiptAddress');
            $orderAddressModel = Loader::model('tradingOrderAddress');

            $address_item = $addressModel->getItem(array('app_id'=>appId(),'id'=>$data['address']['id']));
            $address['address'] = $address_item['detail_address'];
            $address['consignee'] = $address_item['consignee'];
            $address['contact_mobile'] = $address_item['contact_mobile'];
            $address['zip_code'] = $address_item['zip_code'];
            $address['telephone'] = $address_item['telephone'];
            $address['member_id'] = $data['member_id'];
            $address['order_id'] = $id;
            if(!$orderAddressModel->add($address)){
                $this->rollback();
                return false;
            }
        }else{//买家自提
            //买家自提信息
            $shippingModel = Loader::model('tradingOrderShipping');
            $orderAddressModel = Loader::model('tradingOrderAddress');
            $data['shipping']['member_id'] = $data['member_id'];
            $data['shipping']['order_id'] = $id;
            if(!$shippingModel->add($data['shipping'])){
                $this->rollback();
                return false;
            }

            //写入交收地
            $repertory_info = $this->productService->getRepertoryByProductId($product_data[0]['product_id']);
            $repertory_data = array(
                'consignee'=>$repertory_info['contact'],
                'contact_mobile'=>$repertory_info['contact_mobile'],
                'address'=>$repertory_info['repertory_address'],
                'name'=>$repertory_info['repertory_name'],
                'member_id'=>$data['member_id'],
                'order_id'=>$id,
            );
            if(!$orderAddressModel->add($repertory_data)){
                $this->rollback();
                return false;
            }
        }

        //交易模式为直接交易需要生成合同
        if($data['order_mode'] == $orderModel::DIRECTRADE){
            if($data['pay_way']==$orderModel::PAY_WAY_ONLINE){//线上支付
                $final_payment_time = $last_time;
            }else{
                $final_payment_time = '';
            }

            if(!$this->contractService->addContract($id,$data['member_id'],$final_payment_time)){
                $this->rollback();
                return false;
            }
            $log_type = 0;
        }elseif($data['order_mode'] == $orderModel::B2CCONFIRM){//双方确认模式
            $log_type = 1;
        }


        //生成用户消息
        if(!$this->addMessage($data['member_id'],$order_no,'order_create')){
            $this->rollback();
            return false;
        }

        //生成订单日志
        $log_data = array(
            'order_id'=>$id,
            'content'=>$this->getOrderLogText('0',$log_type),
            'date'=>myNow(),
            'member_id'=>$data['member_id'],
        );
        if(!$this->orderLogModel->add($log_data)){
            $this->rollback();
            return false;
        }
        if($data['order_mode'] == $orderModel::DIRECTRADE){//交易模式为直接交易
            //短信&消息提醒
            $remind_type = $data['pay_way']==$orderModel::PAY_WAY_ONLINE?'下单成功（线上）规则':'下单成功（线下）规则';
            $this->remindService->commandRemind(
                $remind_type,
                array( '订单号' => $order_no,
                    '截止付款时间' => $last_time),
                $data['member_id']
            );
        }elseif($data['order_mode'] == $orderModel::B2CCONFIRM){//交易模式为双方确认模式
            //短信&消息提醒
            $this->remindService->commandRemind(
                '下单成功（双方确认模式）规则',
                array( '订单号' => $order_no),
                $data['member_id']
            );
        }

        $this->commit();
        return $id;
    }

    /**
     * 用户议价 todo 第二期
     * @param $order_id 订单id
     * @param $member_id 用户id
     * @param $data 更新数组
     * @return bool
     */
    public function userBargaining($order_id,$member_id,$data){
        $orderModel = $this->orderModel;

        $order_info = $orderModel->getItem(array('id'=>$order_id,'app_id'=>appId()));

        if(!$order_info) return false;
        if($order_info['member_id'] != $member_id) return false;

        $data['order_status'] = $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION;
        return $orderModel->update($data,$order_id);
    }

    /**
     * 运营商确认
     * @param $order_id
     * @return bool
     */
    public function merchantConfirmation($order_id){
        $orderModel = $this->orderModel;

        $order_info = $orderModel->getItem(array('id'=>$order_id,'app_id'=>appId()));

        if(!$order_info) return false;

        $data['order_status'] = $orderModel::WAIT_FOR_USER_CONFIRMATION;
        $bool1 = $orderModel->update($data,$order_id);

        //生成订单日志
        $log_data = array(
            'order_id'=>$order_id,
            'content'=>$this->getOrderLogText('1',1),
            'date'=>myNow(),
            'member_id'=>$order_info['member_id'],
        );
        $this->beginTransaction();
        $bool2 = $this->orderLogModel->add($log_data);

        if(!$bool1 || !$bool2){
            $this->rollback();
            return false;
        }
        //短信&消息提醒
        $this->remindService->commandRemind(
            '卖家确认订单规则',
            array( '订单号' => $order_info['order_no']),
            $order_info['member_id']
        );
        $this->commit();
        return true;
    }

    /**
     * 用户二次确认
     * @param $order_id
     * @param $member_id
     * @return bool
     */
    public function userSecondConfirmation($order_id,$member_id){
        $orderModel = $this->orderModel;

        $order_info = $orderModel->getItem(array('id'=>$order_id,'app_id'=>appId()));

        if(!$order_info) return false;
        if($order_info['member_id'] != $member_id) return false;

        $order_life = C('order_life');
        $last_time = date('Y-m-d H:i:s',strtotime($order_info['order_time'])+$order_life*60);
        $data['order_status'] = $orderModel::ORDER_STATUS_UNPAY;

        $this->beginTransaction();
        $bool1 = $orderModel->update($data,$order_id);
        //用户二次确认完成需要生成合同
        if($data['pay_way']==$orderModel::PAY_WAY_ONLINE){//线上支付
            $final_payment_time = $last_time;
        }else{
            $final_payment_time = '';
        }
        $bool2 = $this->contractService->addContract($order_id,$member_id,$final_payment_time);
        //生成订单日志
        $log_data = array(
            'order_id'=>$order_id,
            'content'=>$this->getOrderLogText('2',1),
            'date'=>myNow(),
            'member_id'=>$order_info['member_id'],
        );
        $bool3 = $this->orderLogModel->add($log_data);

        if(!$bool1 || !$bool2 || !$bool3){
            $this->rollback();
            return false;
        }
        //短信&消息提醒
        $remind_type = $order_info['pay_way']==$orderModel::PAY_WAY_ONLINE?'买家确认订单（线上）规则':'买家确认订单（线下）规则';
        $this->remindService->commandRemind(
            $remind_type,
            array( '订单号' => $order_info['order_no'],
                '截止付款时间' => $last_time),
            $member_id
        );
        $this->commit();
        return true;
    }

    /**
     * 此编辑订单(运营商编辑确认议价)
     * @param array $data 需要更改的信息
     * @param array $id 订单id
     * @return bool|int
     */
    public function editOrder($data,$id){
        $orderModel = $this->orderModel;

        $change_shipp = false;
        $change_addr = false;
        $change_price = false;
        $change_shi = false;

        if(!isset($data['product']['product_id'])) return -1;//订单没有产品

        $order_info = $orderModel->getItem(array('id'=>$id,'app_id'=>appId()));

        if(!$order_info) return -3;

        //运营商确认议价
        if($order_info['order_status'] == $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION){
            $data['order_status'] = $orderModel::WAIT_FOR_USER_CONFIRMATION;
        }

        if($data['shipping_way'] != $order_info['shipping_way']) $change_shi = true;

        //开启事物
        $this->beginTransaction();
        if(($order_info['order_mode'] == $orderModel::DIRECTRADE && $order_info['order_status'] == $orderModel::ORDER_STATUS_UNPAY)
            || ($order_info['order_mode'] != $orderModel::DIRECTRADE && $order_info['order_status'] <= $orderModel::WAIT_FOR_MERCHANT_CONFIRMATION)
        ){
            //产品信息是否更改
            $total_actual_price = 0;
            $product_data = array();
            foreach ($data['product']['product_id'] as $k => $v) {

                //$product_price = $product_arr[$v]['sales_price'];
                $product_actual_price = setFloat($data['product']['product_actual_price'][$k], 2);
                $total_actual_price += $product_actual_price;
                $product_data[] = array(
                    'product_id' => $v,
                    'order_id' => $id,
                    //'product_price'=>$product_price,//实际单价
                    'product_actual_price' => $product_actual_price,
                );
            }
            $data['actual_amount'] = $total_actual_price;
            if (bccomp($order_info['actual_amount'], $total_actual_price, 2) != 0) $change_price = true;

            foreach ($product_data as $v) {
                if (!$this->orderProductModel->updates($v, array('product_id' => $v['product_id'], 'member_id' => $data['member_id'], 'order_id' => $id))) {
                    $this->rollback();
                    return false;
                }
            }
        }else{
            $total_actual_price = $order_info['actual_amount'];
        }

        if(!$orderModel->update($data,$id)){
            $this->rollback();
            return false;
        }


        //配送方式 卖家配送--用户收货地址  自提--用户自提信息
        $shippingModel = Loader::model('tradingOrderShipping');
        $orderAddressModel = Loader::model('tradingOrderAddress');

        if($data['shipping_way'] == $orderModel::SHIPPING_WAY_SELLER){//卖家配送
            if($data['address']['id']){
                //收货地址
                $addressModel = Loader::model('memberReceiptAddress');

                $address_item = $addressModel->getItem(array('app_id'=>appId(),'id'=>$data['address']['id']));
                $address['address'] = $address_item['detail_address'];
                $address['consignee'] = $address_item['consignee'];
                $address['contact_mobile'] = $address_item['contact_mobile'];
                $address['zip_code'] = $address_item['zip_code'];
                $address['telephone'] = $address_item['telephone'];
                $address['member_id'] = $data['member_id'];
                $address['order_id'] = $id;
                $where = array('order_id'=>$id,'app_id'=>appId());
                if($change_shi){//有更改交收方式 删除买家自提信息 写入买家收货信息
                    $bool1 = $shippingModel->deletes($where);
                    $bool2 = $orderAddressModel->deletes($where);
                    $bool3 = $orderAddressModel->add($address);
                    if(!$bool1 || !$bool2 || !$bool3){
                        $this->rollback();
                        return false;
                    }
                }else{//更新买家收货信息
                    if(!$orderAddressModel->updates($address,$where)){
                        $this->rollback();
                        return false;
                    }
                    $change_addr = true;
                }
            }

        }else{//买家自提
            //买家自提信息
            $data['shipping']['member_id'] = $data['member_id'];
            $data['shipping']['order_id'] = $id;
            $where = array('order_id'=>$id,'app_id'=>appId());
            if($change_shi){//有更改交收方式 删除买家收货信息 写入买家自提信息
                $bool1 = $orderAddressModel->deletes($where);
                $bool2 = $shippingModel->add($data['shipping']);
                //写入交收地
                $product_info = $this->orderProductModel->getItem(array('order_id'=>$id),'product_id');
                $repertory_info = $this->productService->getRepertoryByProductId($product_info['product_id']);
                $repertory_data = array(
                    'consignee'=>$repertory_info['contact'],
                    'contact_mobile'=>$repertory_info['contact_mobile'],
                    'address'=>$repertory_info['repertory_address'],
                    'name'=>$repertory_info['repertory_name'],
                    'member_id'=>$data['member_id'],
                    'order_id'=>$id,
                );
                $bool3 = $orderAddressModel->add($repertory_data);
                if(!$bool1 || !$bool2 || !$bool3){
                    $this->rollback();
                    return false;
                }
            }else{//更新买家收货信息
                $res = $shippingModel->getItem($where);
                if($res['shipping_fullname'] != $data['shipping']['shipping_fullname']
                    || $res['shipping_mobile'] != $data['shipping']['shipping_mobile']
                    || $res['shipping_car_card'] != $data['shipping']['shipping_car_card']
                    || $res['shipping_id_card'] != $data['shipping']['shipping_id_card']
                    || $res['shipping_time'] != $data['shipping']['shipping_time']
                    || $res['shipping_remark'] != $data['shipping']['shipping_remark']
                ){
                    if(!$shippingModel->updates($data['shipping'],$where)){
                        $this->rollback();
                        return false;
                    }
                    $change_shipp = true;
                }

            }
        }

        //更改合同
        $contractModel = Loader::model('tradingContract');
        if(!$this->contractService->updateContract($id,$data['member_id'],$contractModel::PROGRESS_CONTRACT_GREATE,$total_actual_price,$data['pay_way'])){
            $this->rollback();
            return false;
        }
        $content = '';
        if($change_price){
            $content .= '价格已被修改；';
        }

        if($change_addr){
            $content .= '地址信息已被修改；';
        }

        if($change_shipp){
            $content .= '自提信息已被修改；';
        }
        if($change_shi){
            $content .= '交收方式已被修改；';
        }
        if($content){
            $content = '您的订单'.$content;
            //生成订单日志
            $log_data = array(
                'order_id'=>$id,
                'content'=>$content,
                'date'=>myNow(),
                'member_id'=>$data['member_id'],
            );
            if(!$this->orderLogModel->add($log_data)){
                $this->rollback();
                return false;
            }
        }

        $this->commit();
        return 1;
    }

    /**
     * 订单详情信息
     * @param string $id 订单id
     * @param string $no 订单号
     * @param string $member_id 会员id
     * @return mixed|null
     */
    public function getDetail($id,$no=null,$member_id=null){
        $orderModel = $this->orderModel;
        $invoiceService = Beans::get('trading.tradingInvoice.service');
        if($id){
            $item = $this->orderModel->getItem($id);
            if(!$item) return NULL;
        }else{
            if($no){
                $item = $this->orderModel->getItem(array('order_no'=>$no));
                if(!$item) return null;
                $id = $item['id'];
            }else{
                return null;
            }
        }
        if($item['app_id'] != appId()){
            return 'denied';//没有权限
        }
        if($member_id && $member_id != $item['member_id']){
            return 'denied';//没有权限
        }

        //获取订单的商品信息
        $product = $this->orderProductModel->getItems(array('order_id'=>$id));
        $invoice_data = $invoiceService->getInvoiceByOrderId($id);
        //var_dump($invoice_data);
        $item['delivery_time'] = $invoice_data['delivery_time'];
        $item['confirm_delivery_time'] = $invoice_data['confirm_delivery_time'];
        $productIds = array();
        $product_new = array();
        foreach($product as $v){
            $productIds[] = $v['product_id'];
            $product_new[$v['product_id']] = $v;
        }
        $product_items = $this->productService->getProductsByIds($productIds,$item['member_id']);
        foreach($product_items as $v){
            $product_total_price = bcmul($product_new[$v['id']]['product_price'],$product_new[$v['id']]['product_quantity'],2);//产品原总价
            $product_new[$v['id']]['max_volume'] = setFloat($v['quantity']-$v['freeze_quantity'],3);
            $product_new[$v['id']]['min_volume'] = setFloat($v['min_volume'],3);
            $product_new[$v['id']]['product_no'] = $v['product_no'];
            $product_new[$v['id']]['sales_price'] = setFloat($v['sales_price'],2);
            $product_new[$v['id']]['product_total_price'] = $product_total_price;
            $product_new[$v['id']]['discount'] = bcsub($product_new[$v['id']]['product_actual_price'],$product_total_price,2);
        }

        $orderAddressModel = Loader::model('tradingOrderAddress');
        $address_item = $orderAddressModel->getItem(array('order_id'=>$id));
        $item['address'] = $address_item;

        $shippingModel = Loader::model('tradingOrderShipping');
        $shipping_item = $shippingModel->getItem(array('order_id'=>$id));
        $item['shipping'] = $shipping_item;

        //会员信息
        $memberService=Beans::get('member.member.service');
        $item['company'] = $memberService->getUsernameById($item['member_id']);
        //var_dump($item['company']);
        $item['log'] = $this->orderLogModel->getItems(array('app_id'=>appId(),'order_id'=>$id),array('id','date','content'),array('id'=>'-1'));

        $item['product'] = $product_new;
        return $item;
    }

    /**
     * 订单列表筛选
     * @param $data 筛选数据
     * @param int $pagesize 每页数量
     * @param int $page 分页
     * @return array
     */
    public function getOrderList($data,$pagesize=10,$page=1){
        $orderModel = $this->orderModel;
        $page = $page>0?$page:1;
        $offset = $pagesize * ($page - 1); //计算记录偏移量
        $where = '1';
        $where .= " AND tro.app_id='" . appId() . "'";
        if($data['member_id'] != ''){
            $where .= " AND tro.member_id='" . $data['member_id'] . "'";
        }
        if($data['order_no'] != ''){
            $where .= " AND tro.order_no LIKE '%" . $data['order_no'] . "%'";
        }
        if($data['order_status'] != '' && $data['order_status'] != 'all'){
            $where .= " AND tro.order_status='" . $data['order_status'] . "'";
        }
        if($data['shipping_fullname'] != ''){
            $where .= " AND tro.shipping_way=" . $orderModel::SHIPPING_WAY_BUYER . " AND tros.shipping_fullname LIKE '%" . $data['shipping_fullname'] . "%'";
        }
        if($data['shipping_mobile'] != ''){
            $where .= " AND tro.shipping_way=" . $orderModel::SHIPPING_WAY_BUYER . " AND tros.shipping_mobile LIKE '%" . $data['shipping_mobile'] . "%'";
        }
        if($data['consignee'] != ''){
            $where .= " AND tro.shipping_way=" . $orderModel::SHIPPING_WAY_SELLER . " AND troa.consignee LIKE '%" . $data['consignee'] . "%'";
        }
        if($data['contact_mobile'] != ''){
            $where .= " AND tro.shipping_way=" . $orderModel::SHIPPING_WAY_SELLER . " AND troa.contact_mobile LIKE '%" . $data['contact_mobile'] . "%'";
        }
        if($data['pay_s_time'] != ''){
            $where .= " AND tro.pay_time>'" . $data['pay_s_time'] . "'";
        }
        if($data['pay_e_time'] != ''){
            $where .= " AND tro.pay_time<='" . $data['pay_e_time'] . " 23:59:59'";
        }
        if($data['order_s_time'] != ''){
            $where .= " AND tro.order_time>'" . $data['order_s_time'] . "'";
        }
        if($data['order_e_time'] != ''){
            $where .= " AND tro.order_time<='" . $data['order_e_time'] . " 23:59:59'";
        }
        if( $data['id'] != '' ){
            $where .= " AND tro.id in{$data['id']}";
        }

        $order = "ORDER BY tro.order_time DESC";
        $limit = "Limit $offset,$pagesize";
        $count_sql = "SELECT count(*) FROM trading_order tro
                LEFT JOIN trading_order_shipping tros ON tro.id=tros.order_id
                LEFT JOIN trading_order_address troa ON tro.id=troa.order_id
                WHERE $where
                ";

        $total = $this->orderModel->getDB()->excute($count_sql)->fetchColumn();

        $sql = "SELECT tro.*,tros.shipping_fullname,tros.shipping_mobile,troa.consignee,troa.contact_mobile FROM trading_order tro
                LEFT JOIN trading_order_shipping tros ON tro.id=tros.order_id
                LEFT JOIN trading_order_address troa ON tro.id=troa.order_id
                WHERE $where $order $limit
                ";

        $items = $this->orderModel->getDB()->excute($sql)->fetchAll($fetch_style = 2);

        return array("items" => $items, "total" => $total);
    }

    /**
     * 支付
     * @param string $id 订单id
     * @param string $dasu_id 大塑支付id
     * @return bool
     */
    public function payOrder($id,$dasu_id){
        $contractModel = Loader::model('tradingContract');
        $orderModel = $this->orderModel;
        $where = array('id'=>$id,'app_id'=>appId());
        $info = $orderModel->getItem($where);
        if(!$info) return false;
        if($info['order_status'] != $orderModel::ORDER_STATUS_UNPAY || $info['pay_way'] != $orderModel::PAY_WAY_ONLINE){//线下付款不走这方法
            return false;
        }
        //开启事物
        $this->beginTransaction();

        //获取运营商大塑支付id
        $api_data['appid'] = appId();
        $url = "api/user/getUserByAppId";

        $result = PayApiClient::send($url, $api_data);
        if ($result->isSucess()){
            $app_res = $result->getItem();
            $payeeUserId = $app_res['userid'];
        }else{
            return false;//没有获取到运营商支付id
        }

        //调取大塑支付API
        $api_arr['orderNo'] = $info['order_no'];
        $api_arr['payUserId'] = $dasu_id;
        $api_arr['payeeUserId'] = $payeeUserId;
        $api_arr['amount'] = $info['actual_amount'];
        $url = "api/order/orderPay";

        $result = PayApiClient::send($url, $api_arr);
        if ($result->isSucess()){
            $pay_data = array(
                'order_status'=>$orderModel::ORDER_STATUS_TO_BE_SHIPPED,//代发货，大塑支付运营商不需要确认收款
                'pay_time'=>myNow(),
            );

            //更新订单状态
            $bool1 = $orderModel->updates($pay_data,$where);

            //合同进度的更新 买方付款
            $bool2 = $this->contractService->updateContract($id,$info['member_id'],$contractModel::PROGRESS_BUYER_MONEY_PAYED,$info['actual_amount'],$info['pay_way']);


            //如订单为自提方式则生成提货单
            $bool3 = true;
            if($info['shipping_way'] == $orderModel::SHIPPING_WAY_BUYER){
                $memberService = Beans::get('member.member.service');
                $company_info = $memberService->getCompanyById($info['member_id'],'company,legal_person,mobile');
                $member_info = $memberService->getUsernameById($info['member_id']);
                //获取仓库id
                $product_info = $this->orderProductModel->getItem(array('order_id'=>$id),'product_id');
                $repertory_info = $this->productService->getRepertoryByProductId($product_info['product_id']);
                //提货单号
                $MyNumber = new MyNumber(appId());
                $lading_no = $MyNumber->build_no('th');
                $lading_arr = array(
                    'order_id'=>$id,
                    'lading_no'=>$lading_no,
                    'order_no'=>$info['order_no'],
                    'username'=>$member_info['username'],
                    'company'=>$company_info['company'],
                    'legal_person'=>$company_info['legal_person'],
                    'mobile'=>$company_info['mobile'],
                    'repertory_name'=>$repertory_info['repertory_name'],
                    'address'=>$repertory_info['repertory_address'],
                    'contact'=>$repertory_info['contact'],
                    'contact_mobile'=>$repertory_info['contact_mobile'],
                    'member_id'=>$info['member_id'],
                );
                $ladingModel = Loader::model('tradingOrderLading');
                if(!$ladingModel->add($lading_arr)){
                    $bool3 = false;
                }
            }


            //生成用户消息
            $bool4 = $this->addMessage($info['member_id'],$info['order_no'],'order_pay');

            //生成订单日志
            $log_data = array(
                'order_id'=>$id,
                'content'=>$this->getOrderLogText(1),
                'date'=>myNow(),
                'member_id'=>$info['member_id'],
            );
            $bool5 = $this->orderLogModel->add($log_data);

            if(!$bool1 || !$bool2 || !$bool3 || !$bool4 || !$bool5){
                $msg = "订单id：{$id} 更新错误，付款人id：{$dasu_id} 收款人id：{$payeeUserId} 付款金额：".$info['actual_amount']."待返还";
                Log::info($msg,'fund');
                $this->rollback();
                return false;
            }

            //短信&消息提醒
            $this->remindService->commandRemind(
                '线上（大塑支付）规则',
                array( '订单号' => $info['order_no']),
                $info['member_id']
            );

            $this->commit();
            return true;
        }else{//支付失败
            Log::info($result->getMessage());
            $this->rollback();
            return false;
        }
    }

    /**
     * 确认收款
     * @param string $order_id 订单id
     * @param string $ids 流水id组
     * @return bool
     */
    public function confirmOrderPay($order_id,$ids){
        $contractModel = Loader::model('tradingContract');
        $orderModel = $this->orderModel;
        $where = array('id'=>$order_id,'app_id'=>appId());
        $info = $orderModel->getItem($where);
        if(!$info) return false;
        if($info['order_status'] != $orderModel::ORDER_STATUS_UNPAY || $info['pay_way'] != $orderModel::PAY_WAY_OFFLINE){
            return false;
        }

        //写入线下支付流水（订单绑定银行流水）
        $api_arr['orderNO'] = $info['order_no'];
        $api_arr['serialIds'] = $ids;
        $api_arr['orderAmount'] = $info['actual_amount'];
        $url = "api/order/confirmFundLog";
        $result = PayApiClient::send($url, $api_arr);
        if ($result->isSucess()){
            $this->beginTransaction();
            //更新订单状态
            $bool1 = $orderModel->updates(array('order_status'=>$orderModel::ORDER_STATUS_TO_BE_SHIPPED,'pay_time'=>myNow()),$where);

            //合同进度更新 确认收款
            $bool2 = $this->contractService->updateContract($order_id,$info['member_id'],$contractModel::PROGRESS_SELLER_MONEY_COLLECTION,$info['actual_amount'],$info['pay_way']);

            //如订单为自提方式则生成提货单
            $bool3 = true;
            if($info['shipping_way'] == $orderModel::SHIPPING_WAY_BUYER){
                $memberService = Beans::get('member.member.service');
                $company_info = $memberService->getCompanyById($info['member_id'],'company,legal_person,mobile');
                $member_info = $memberService->getUsernameById($info['member_id']);
                //获取仓库id
                $product_info = $this->orderProductModel->getItem(array('order_id'=>$order_id),'product_id');
                $repertory_info = $this->productService->getRepertoryByProductId($product_info['product_id']);
                //提货单号
                $MyNumber = new MyNumber(appId());
                $lading_no = $MyNumber->build_no('th');
                $lading_arr = array(
                    'order_id'=>$order_id,
                    'lading_no'=>$lading_no,
                    'order_no'=>$info['order_no'],
                    'username'=>$member_info['username'],
                    'company'=>$company_info['company'],
                    'legal_person'=>$company_info['legal_person'],
                    'mobile'=>$company_info['mobile'],
                    'repertory_name'=>$repertory_info['repertory_name'],
                    'address'=>$repertory_info['repertory_address'],
                    'contact'=>$repertory_info['contact'],
                    'contact_mobile'=>$repertory_info['contact_mobile'],
                    'member_id'=>$info['member_id'],
                );
                $ladingModel = Loader::model('tradingOrderLading');
                if(!$ladingModel->add($lading_arr)){
                    $bool3 = false;
                }
            }

            //生成订单日志
            $log_data = array(
                'order_id'=>$order_id,
                'content'=>$this->getOrderLogText(7),
                'date'=>myNow(),
                'member_id'=>$info['member_id'],
            );
            $bool4 = $this->orderLogModel->add($log_data);

            if(!$bool1 || !$bool2 || !$bool3 || !$bool4){
                $msg = "订单id：{$order_id} 更新错误，银行流水id组：" . json_encode($ids) . " 订单金额：".$info['actual_amount'];
                Log::info($msg,'fund');
                $this->rollback();
                return false;
            }
            //短信&消息提醒
            $this->remindService->commandRemind(
                '线下（确认收款）规则',
                array( '订单号' => $info['order_no']),
                $info['member_id']
            );
            $this->commit();
            return 1;
        }else{
            Log::info($result->getMessage());
            return $result->getMessage();
        }
    }

    /**
     * 发货
     * @param string $id 订单id
     * @param string $data 配送信息
     * @return bool
     */
    public function delivery($id,$data=null){
        $invoiceService = Beans::get('trading.tradingInvoice.service');
        $contractModel = Loader::model('tradingContract');
        $orderModel = $this->orderModel;
        $where = array('id'=>$id,'app_id'=>appId());
        $info = $orderModel->getItem($where);
        if(!$info) return false;
        if($info['order_status'] != $orderModel::ORDER_STATUS_TO_BE_SHIPPED){
            return false;
        }
        $this->beginTransaction();

        //更改订单状态
        $bool1 = $orderModel->updates(array('order_status'=>$orderModel::ORDER_STATUS_SHIPPED),$where);

        //合同进度的更新 卖家发货
        $product_info = $this->orderProductModel->getItem(array('order_id'=>$id),'SUM(product_quantity) as quantity');
        $bool2 = $this->contractService->updateContract($id,$info['member_id'],$contractModel::PROGRESS_SELLER_GOODS_DELIVERY,$product_info['quantity'],$info['pay_way']);

        //生成发货单
        $bool3 = $invoiceService->addInvoice($id,$info['member_id'],myNow());

        //生成销售单
        $saleService = Beans::get('trading.tradingSale.service');
        $bool4 = $saleService->addSale($id);

        //生成订单日志
        $bool5 = true;
        for($i=2;$i<4;$i++){
            $log_data = array(
                'order_id'=>$id,
                'content'=>$this->getOrderLogText($i),
                'date'=>myNow(),
                'member_id'=>$info['member_id'],
            );

            $bool5 = $bool5&&$this->orderLogModel->add($log_data);
        }

        if(!$bool1 || !$bool2 || !$bool3 || !$bool4 || !$bool5){
            $this->rollback();
            return false;
        }

        if($info['shipping_way'] == $orderModel::SHIPPING_WAY_SELLER){//卖家配送
            //生成订单配送单
            $shippingModel = Loader::model('tradingOrderShipping');

            $data['member_id'] = $info['member_id'];
            $data['order_id'] = $id;
            if(!$shippingModel->add($data)){
                $this->rollback();
                return false;
            }

            //短信&消息提醒
            $this->remindService->commandRemind(
                '发货成功（卖家配送）规则',
                array('订单号' => $info['order_no'], '送货人姓名' => $data['shipping_fullname'], '送货人手机号码' => $data['shipping_mobile']),
                $info['member_id']
            );
        }else{

            //短信&消息提醒
            $this->remindService->commandRemind(
                '发货成功（买家自提）规则',
                array( '订单号' => $info['order_no']),
                $info['member_id']
            );
        }

        $this->commit();
        return true;
    }

    /**
     * 确认收货
     * @param string $id 订单id
     * @return bool
     */
    public function confirmDelivery($id,$dasu_id){
        $invoiceService = Beans::get('trading.tradingInvoice.service');
        $contractModel = Loader::model('tradingContract');
        $orderModel = $this->orderModel;

        $where = array('id'=>$id,'app_id'=>appId());
        $info = $orderModel->getItem($where);
        if(!$info) return false;
        if($info['order_status'] != $orderModel::ORDER_STATUS_SHIPPED){
            return false;
        }
        $this->beginTransaction();
        //线上支付 需要调取saas接口
        $isOnlinePay = $info['pay_way'] == $orderModel::PAY_WAY_ONLINE?true:false;
        if($isOnlinePay){
            //获取运营商大塑支付id
            $api_data['appid'] = appId();
            $url = "api/user/getUserByAppId";

            $result = PayApiClient::send($url, $api_data);
            if ($result->isSucess()){
                $app_res = $result->getItem();
                $payeeUserId = $app_res['userid'];
            }else{
                return false;//没有获取到运营商支付id
            }

            //调取确认收货API
            $api_arr['orderNo'] = $info['order_no'];
            $api_arr['payUserId'] = $dasu_id;
            $api_arr['payeeUserId'] = $payeeUserId;
            $url = "api/order/orderConfirm";

            $result = PayApiClient::send($url, $api_arr);
            if ($result->isSucess()){
            }else{
                Log::info($result->getMessage());
                $this->rollback();
                return false;
            }
        }

        //更改订单状态 确认收货/订单完成
        $bool1 = $orderModel->updates(array('order_status'=>$orderModel::ORDER_STATUS_COMPLETED),$where);

        //扣除产品库存
        $bool2 = true;
        $orderProducts = $this->orderProductModel->getItems(array('order_id'=>$id));
        foreach($orderProducts as $v){

            $bool2 = $bool2&&$this->productService->thawStock($v['product_id'],$v['product_quantity']);

        }

        //合同进度的更新 买方确认收货
        $product_info = $this->orderProductModel->getItem(array('order_id'=>$id),'SUM(product_quantity) as quantity');
        $bool3 = $this->contractService->updateContract($id,$info['member_id'],$contractModel::PROGRESS_BUYER_GOODS_RECEIPT,$product_info['quantity'],$info['pay_way']);

        //更新发货单
        $bool4 = $invoiceService->updateInvoice($id,$info['member_id'],myNow());

        $bool5 = true;
        //生成订单日志
        for($i=4;$i<6;$i++){
            $log_data = array(
                'order_id'=>$id,
                'content'=>$this->getOrderLogText($i),
                'date'=>myNow(),
                'member_id'=>$info['member_id'],
            );

            $bool5 = $bool5&&$this->orderLogModel->add($log_data);
        }

        //生成用户消息
        $bool6 = $this->addMessage($info['member_id'],$info['order_no'],'order_confirmed_receipt');

        if(!$bool1 || !$bool2 || !$bool3 || !$bool4 || !$bool5 || !$bool6){

            if($isOnlinePay){
                $msg = "订单id：{$id} 确认收货更新错误，付款人id：{$dasu_id} 收款人id：{$payeeUserId} 金额：".$info['actual_amount'];
                Log::info($msg,'fund');
            }

            $this->rollback();
            return false;
        }

        //短信&消息提醒
        $this->remindService->commandRemind(
            '收货成功规则',
            array( '订单号' => $info['order_no']),
            $info['member_id']
        );

        $this->commit();
        return true;

    }

    /**
     * 取消订单
     * @param string $id 订单id
     * @param string $type 取消类型 0为管理员，1为用户
     * @return bool
     */
    public function cancelOrder($id,$type=0){
        $orderModel = $this->orderModel;

        $where = array('id'=>$id,'app_id'=>appId());
        $info = $orderModel->getItem($where);
        if(!$info) return false;
        if($info['order_status'] > $orderModel::ORDER_STATUS_UNPAY){
            return false;
        }
        $this->beginTransaction();
        $data = array(
            'order_status'=>$orderModel::ORDER_STATUS_CANCELED,//取消订单
        );
        //更新订单状态
        $bool1 = $orderModel->updates($data,$where);

        //扣除冻结库存
        $bool2 = true;
        $orderProducts = $this->orderProductModel->getItems(array('order_id'=>$id));
        foreach($orderProducts as $v){

            $bool2 = $bool2&&$this->productService->thawStock($v['product_id'],$v['product_quantity'],true);

        }

        if($type==0){
            $logType = 8;
        }else{
            //生成用户消息
            if(!$this->addMessage($info['member_id'],$info['order_no'],'order_cancel')){
                $this->rollback();
                return false;
            }
            $logType = 9;
        }

        //生成订单日志
        $log_data = array(
            'order_id'=>$id,
            'content'=>$this->getOrderLogText($logType),
            'date'=>myNow(),
            'member_id'=>$info['member_id'],
        );
        $bool3 = $this->orderLogModel->add($log_data);
        if(!$bool1 || !$bool2 || !$bool3){
            $this->rollback();
            return false;
        }
        $this->commit();
        return true;
    }



    /**删除功能去除**/
    public function deletes($conditions){
        return true;
    }
    public function delete($id){
        return true;
    }





    /**
     * 定时任务 超出设定时间关闭未支付订单
     */
    public function batchClose(){
        $settingService = Beans::get('admin.adminSetting.service');
        $life_configs = $settingService->getAllAppSetting('order_life');
        $orderModel = $this->orderModel;
        foreach ($life_configs as $val){
            $live_time = $val['value']*60;//转成秒
            $items = $orderModel->getItems(array('order_status'=>array('<'=>$orderModel::ORDER_STATUS_UNPAY),'pay_way'=>$orderModel::PAY_WAY_ONLINE,'app_id'=>$val['app_id']));
            foreach($items as $v){
                if((time()-strtotime($v['order_time']))>($live_time)){//订单超出设置的存活周期

                    //取消订单
                    $this->closeOrder($v['id'],$v['member_id'],$val['app_id']);

                }
            }
        }
        echo '执行成功--'.myNow();
    }

    public function closeOrder($order_id,$member_id,$app_id){
        $orderModel = $this->orderModel;

        //开启事物
        $this->beginTransaction();

        //更新订单状态
        $bool1 = $orderModel->updates(array('order_status'=>$orderModel::ORDER_STATUS_CANCELED),array('id'=>$order_id,'app_id'=>$app_id));

        //扣除冻结库存
        $bool2 = true;
        $orderProducts = $this->orderProductModel->getItems(array('order_id'=>$order_id));
        foreach($orderProducts as $v){
            $bool2 = $bool2&&$this->productService->thawStock($v['product_id'],$v['product_quantity'],true);
        }

        //生成订单日志
        $log_data = array(
            'order_id'=>$order_id,
            'content'=>$this->getOrderLogText(6),
            'date'=>myNow(),
            'member_id'=>$member_id,
            'app_id'=>$app_id,
        );
        $bool3 = $this->orderLogModel->add($log_data);

        if(!$bool1 || !$bool2 || !$bool3){
            $this->rollback();
            Log::info('订单id:'.$order_id.' 取消失败！');
            return false;
        }

        $this->commit();
        return true;

    }



    /**
     * 内部调取API
     */

    /**
     * 统计已完成订单总量/销售额
     * @param string $type 1为完成订单量 2为销售额
     * @param string $startTime
     * @param string $endTime
     * @return int
     */
    public function getTotal($type=1,$startTime=null,$endTime=null){
        $orderModel = $this->orderModel;

        $conditions = " tro.order_status='" . $orderModel::ORDER_STATUS_COMPLETED . "'";//已完成的订单
        $conditions .= " AND tro.app_id='".appId()."'";
        if($startTime) $conditions .= " AND tri.confirm_delivery_time>'" . $startTime . "'";
        if($endTime) $conditions .= " AND tri.confirm_delivery_time<'" . $endTime . "'";

        $field = $type==1?"COUNT(*)":"SUM(actual_amount)";
        $sql = "SELECT $field num FROM trading_order tro INNER JOIN trading_invoice tri ON tro.id=tri.order_id WHERE $conditions";

        $result = $orderModel->query($sql);
        return $result?$result[0]['num']:0;

    }

    /**
     * 统计订单销售量
     * @param string $startTime
     * @param string $endTime
     * @return int
     */
    public function getQuantityTotal($startTime=null,$endTime=null){
        $orderModel = $this->orderModel;

        $conditions = " tro.order_status='" . $orderModel::ORDER_STATUS_COMPLETED . "'";//已完成的订单
        $conditions .= " AND tro.app_id='".appId()."'";
        if($startTime) $conditions .= " AND tri.confirm_delivery_time>'" . $startTime . "'";
        if($endTime) $conditions .= " AND tri.confirm_delivery_time<'" . $endTime . "'";

        $sql = "SELECT SUM(trop.product_quantity) num FROM trading_order tro INNER JOIN trading_order_product trop ON tro.id=trop.order_id INNER JOIN trading_invoice tri ON tro.id=tri.order_id WHERE $conditions";

        $result = $orderModel->query($sql);
        return $result?$result[0]['num']:0;

    }

    public function getOrderSalesVolumeForDays($startTime=null,$endTime=null){
        $orderModel = $this->orderModel;

        $conditions = " tro.order_status='" . $orderModel::ORDER_STATUS_COMPLETED . "'";//已完成的订单
        $conditions .= " AND tro.app_id='".appId()."'";
        if($startTime) $conditions .= " AND tri.confirm_delivery_time>'" . $startTime . "'";
        if($endTime) $conditions .= " AND tri.confirm_delivery_time<'" . $endTime . "'";

        $field = "DATE_FORMAT(tri.confirm_delivery_time,'%Y-%m-%d') days,sum(tro.actual_amount) amount";
        $sql = "SELECT $field FROM trading_order tro INNER JOIN trading_invoice tri ON tro.id=tri.order_id WHERE $conditions group by days";

        $result = $orderModel->query($sql);
        return $result?$result:array();
    }

    /**
     * 统计订单销售量
     * @param string $startTime
     * @param string $endTime
     * @return int
     */
    public function getQuantityForDays($startTime=null,$endTime=null){
        $orderModel = $this->orderModel;

        $conditions = " tro.order_status='" . $orderModel::ORDER_STATUS_COMPLETED . "'";//已完成的订单
        $conditions .= " AND tro.app_id='".appId()."'";
        if($startTime) $conditions .= " AND tri.confirm_delivery_time>'" . $startTime . "'";
        if($endTime) $conditions .= " AND tri.confirm_delivery_time<'" . $endTime . "'";

        $field = "DATE_FORMAT(tri.confirm_delivery_time,'%Y-%m-%d') days,sum(trop.product_quantity) num";
        $sql = "SELECT $field FROM trading_order tro INNER JOIN trading_order_product trop ON tro.id=trop.order_id INNER JOIN trading_invoice tri ON tro.id=tri.order_id WHERE $conditions group by days";

        $result = $orderModel->query($sql);
        return $result?$result:array();
    }
}